#include"queue.h"

void Qinit(Qlist* pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;
}

void Qpush(Qlist* pq, Qdatetype x)
{
	assert(pq);
	Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
	if (newnode == NULL)
	{
		perror("malloc fail:");
		exit(-1);
	}
	newnode->x = x;
	newnode->next = NULL;
	if (pq->head == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}

void Qpop(Qlist* pq)
{
	assert(pq);
	assert(!Qempty(pq));
	Qnode* next = pq->head->next;
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = next;
	}
	else
	{
		free(pq->head);
		pq->head = next;
	}
}

bool Qempty(Qlist* pq)
{
	assert(pq);
	return pq->head == NULL;
}

Qdatetype Qtop(Qlist* pq)
{
	assert(pq);
	assert(!Qempty(pq));
	return pq->head->x;
}

Qdatetype Qback(Qlist* pq)
{
	assert(pq);
	assert(!Qempty(pq));
	return pq->tail->x;
}

int Qsize(Qlist* pq)
{
	assert(pq);
	assert(!Qempty(pq));
	Qnode* cur = pq->head;
	int size = 0;
	while (cur)
	{
		++size;
		cur = cur->next;
	}
	return size;
}

void Qdestory(Qlist* pq)
{
	assert(pq);
	Qnode* cur = pq->head;
	while (cur)
	{
		Qnode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head=pq->tail=NULL;
}

